<template>
	<div class="index">
		    <div class="navBox">
					<div class="title">蓝牙选择</div>
			</div>
			<div class="blueContent">
				<div class="blueBox" v-for="(item,index) of bleDevs" :key="item.deviceId" @click="createBLEConnection(item.deviceId)">
					  <div class="rowTop">
							<!-- <image :src="((isBluedeviceId === 1)?'@/static/connectedBlue.png':'@/static/notconnectedBlue.png')" style="width:30px;height:30px; margin-right: 20rpx;" mode="aspectFit"></image> -->
							<image v-if="isBluedeviceId == item.deviceId"  :src="imageName('/connectedBlue.png')" style="width:30px;height:30px; margin-right: 20rpx;" mode="aspectFit"></image>
							<image v-else :src="imageName('/notconnectedBlue.png')" style="width:30px;height:30px; margin-right: 20rpx;" mode="aspectFit"></image>
							<text>{{item.name}}</text>
					  </div>
				</div>
			</div>
			<div class="refresh" @click="onRefreshClick()">
				<image src="../../static/refresh.png" style="width:60px;height:60px;"></image>
			</div>
	</div>
</template>

<script>
	import JSZip from "jszip";
	import imageName from '@/utils/imageFormat.js';
	export default {
		data() {
			return {
				imageName,
				list: [{
					row1: 'XS16T_BLE',
					row2: '(B2:4A:ED:56:B0:A4)'
				}, ],
				isBluedeviceId:"",
				deviceId: "",
				deviceIdList: [],
				timer2: "",
				bleDevs: [],
				name: "",
				imageValue: [],
			}
		},
		onShow(){
			if(this.$store.state.token == "")
			{
				uni.navigateTo({
					url: `/pages/login/login`
				})
			}
			else
			{
			  this.initBle();
			}
		},
		onHide(){
		   uni.stopBluetoothDevicesDiscovery({
		   	success(res) {
		   		console.log('停止搜索蓝牙', res)
		   	}
		   })
		},
		onUnload(){
		  uni.stopBluetoothDevicesDiscovery({
		  	success(res) {
		  		console.log('停止搜索蓝牙', res)
		  	}
		  })
		},
		methods: {		
			buf2hex(toArrayBuffer) {
				const hexArr = Array.prototype.map.call(
					new Uint8Array(toArrayBuffer),
					function(bit) {
						return ('00' + bit.toString(16)).slice(-2)
					}
				)
				return hexArr.join('')
			},
			jumpToDetail() {
				uni.navigateTo({
					url: `/pages/detail/detail?deviceId=${this.deviceId}&name=${this.name}`
				})
			},
			initBle() {
				console.log('--------------------初始化蓝牙----------------');
				uni.showLoading({
					icon: 'none',
					title: '搜索蓝牙中'
				});
				this.bleDevs = [];
				uni.openBluetoothAdapter({
					success: (res) => { //已打开
						uni.getBluetoothAdapterState({ //蓝牙的匹配状态
							success: (row) => {
								console.log(row)
								// 开始搜索蓝牙设备
								this.startBluetoothDeviceDiscovery();
							},
							fail(error) {
								uni.hideLoading();
								uni.showToast({
									icon: 'none',
									title: '查看手机蓝牙是否打开'
								});
							}
						});

					},
					fail: err => { //未打开 
						uni.showToast({
							icon: 'none',
							title: '查看手机蓝牙是否打开'
						});
					}
				})
			},
			// 开始搜索蓝牙设备
			startBluetoothDeviceDiscovery() {
				this.onBLEConnectionStateChange();
				let _this = this
				uni.startBluetoothDevicesDiscovery({
					success: (res) => {
						console.log('搜索蓝牙外围设备完成', res)
                            setTimeout(() => { //加个延迟、目的是为了设备搜索完毕再获取列表，不然获取为空列表
							// 获取设备列表
							_this.onBluetoothDeviceFound()

						}, 1000)
					},
					fail: (err) => {
						uni.hideLoading();
						console.log(err)
						let _this = this
						if(err.errCode === 10008)
						{
							
						}
					}
				})
			},
			// 获取设备列表
			onBluetoothDeviceFound() {
				let that = this
				this.bleDevs = []
				this.deviceIdList = []
				var deviceid = ''
				uni.getBluetoothDevices({
					success: function(res) {
						uni.hideLoading();
						//过滤掉name为空的设备
						// console.log(res.devices)
						var bluetoothArr = res.devices.filter(function(obj) {
							if (obj.name.indexOf("WeiDian") === 0 && !that.deviceIdList.includes(obj.deviceId)) {
								that.deviceIdList.push(obj.deviceId)
								return obj
							}
						
						})
						that.bleDevs = bluetoothArr;

					},
					fail: function() {
						console.log("搜索蓝牙设备失败");
						uni.hideLoading();
						uni.showToast({
							title: '搜索蓝牙设备失败或附件暂无开启的蓝牙设备',
							icon: 'none',
							duration: 2000
						})
					},
					complete: function() {
						console.log('搜索完成')
						//设备获取完成之后  停止搜索
						// uni.stopBluetoothDevicesDiscovery({
						// 	success(res) {
						// 		console.log('停止搜索蓝牙', res)
						// 	}
						// })
					}
				})
			},
			//选择设备连接把deviceId传进来
			createBLEConnection(deviceId) {
				let that = this
				this.deviceId = deviceId
				this.pageLoading = true
				uni.showLoading({
					title: '加载中'
				})
				//连接蓝牙
				uni.createBLEConnection({
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: this.deviceId,
					success(res) {
						uni.hideLoading();
						that.timer2 = setTimeout(() => {
							let index = ''
							that.bleDevs.forEach((i, key) => {
								if (i.deviceId == that.deviceId) {
									that.name = i.localName;
									that.isBluedeviceId = that.deviceId;
									that.jumpToDetail();
								}
							})
							that.pageLoading = false

						}, 1000)
					},
					fail(res) {
						uni.hideLoading();
						uni.showToast({
							icon: 'none',
							title: '蓝牙连接失败'
						})
					},
					complete: function() {
						console.log('搜索完成')
						//设备获取完成之后  停止搜索
						uni.stopBluetoothDevicesDiscovery({
							success(res) {
								console.log('停止搜索蓝牙', res)
							}
						})
					}
				})
			},
			//断开蓝牙
			onBLEConnectionStateChange() {
				uni.onBLEConnectionStateChange(function(res) {})
			},
			onRefreshClick(){
				 //this.jumpToDetail();
				let _this = this
				uni.stopBluetoothDevicesDiscovery({
					success(res) {
						_this.onBluetoothDeviceFound()
						_this.startBluetoothDeviceDiscovery();
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.index {
		width: 100%;
		height: 100%;
		position: relative;
		// display: flex;
		// flex-direction: column;
		// align-items: center;
		// background-color: #f1f1f1;
		.navBox{
			width: 100%;
			height:180rpx;
			background-color: rgba(127, 189, 244, 1);
			padding-top: 105rpx;
			box-sizing: border-box;
			.title{
				width: 100%;
				text-align: center;
				font-size: 36rpx;
				color: white;
			}
		}
		.blueContent{
			width: 100%;
			padding:0 70rpx;
			box-sizing: border-box;
			.blueBox{
				width: 100%;
				display: flex;
				flex-direction: row;
				border-bottom:2rpx solid rgba(204, 204, 204, 1);
				.rowTop{
					flex: 1;
				   display: flex;
				   flex-direction: row;
				   align-items: center;
				   padding:30rpx 0;
				   box-sizing: border-box;
				}
				
			}
		}
		.refresh{
			width:40rpx;
			height:40rpx;
			position: absolute;
			right:100rpx;
			bottom:200rpx;
		}
	}
</style>